// /src/router/index.ts
import type {Router, RouteRecordRaw} from 'vue-router'
import {createRouter, createWebHistory} from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {useUserStore} from '../store/user'
import {storeToRefs} from 'pinia'

// 站点基础标题
const siteTitle = 'Your Site Name'

// 路由配置
const routes: RouteRecordRaw[] = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/login/index.vue'),
        meta: {
            title: '登录'
        }
    },
    {
        path: '/',
        name: 'Layout',
        component: () => import('../layout/index.vue'),
        children: [
            {
                path: 'home',
                name: 'Home',
                component: () => import('../views/home/index.vue'),
                meta: {
                    title: '首页'
                }
            },
            {
                path: 'example',
                children: [
                    {
                        path: 'table',
                        name: 'Table',
                        component: () => import('../views/example/table/index.vue'),
                        meta: {
                            title: '示例表格'
                        }
                    }
                ]
            }
        ],
        meta: {
            title: ''
        }
    }
    // 在此添加其他路由...
]

// 创建路由实例
const router: Router = createRouter({
    history: createWebHistory(),
    routes
})

// 配置进度条
NProgress.configure({
    showSpinner: false
})

// 免登录白名单
const excludedList: string[] = [
    '/login',
    '/register',
    '/forgot',
    '/',
    '/home',
    '/example/table',
]

// 路由守卫
router.beforeEach((to, from, next) => {
    // 处理标题
    document.title = to.meta.title ? `${siteTitle} - ${to.meta.title}` : siteTitle

    NProgress.start()

    // 白名单检查
    if (excludedList.includes(to.path)) {
        next()
        return
    }

    // 登录验证
    const userStore = useUserStore()
    const { token } = storeToRefs(userStore)

    if (token.value) {
        next()
    } else {
        const redirectPath = from.path !== '/'
            ? `/login?last=${encodeURIComponent(from.path)}`
            : '/login'
        next(redirectPath)
    }
})

router.afterEach(() => {
    NProgress.done()
})

export default router
